﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: FirstOrDefault.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-12-07 11:40 PM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq
{
    public static partial class Linq
    {
        public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Random random)
        {
            var list = source as List<TSource> ?? source.ToList();
            var count = list.Count;

            return count == 0 ? default(TSource) : list.Skip(random.Next(count - 1)).First();
        }

        public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, Boolean> predicate, Random random)
        {
            return source.Where(predicate).FirstOrDefault(random);
        }

        public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Random random)
        {
            var list = source as List<TSource> ?? source.ToList();
            var count = list.Count;

            return count == 0 ? default(TSource) : list.Skip(random.Next(count - 1)).Single();
        }

        public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, Boolean> predicate, Random random)
        {
            return source.Where(predicate).SingleOrDefault(random);
        }

    }
}
